<template>
  <div class="container">
    <van-nav-bar :title="title" fixed class="titleStyle" left-arrow @click-left="onClickLeft" />
    <div class="saveBtnDiv">
      <van-button class="saveBtns" type="primary" native-type="submit" @click="handleSubmit(2)">提交转维修</van-button>
      <van-button class="saveBtns" style="margin-right:5px ;" type="primary" native-type="submit" @click="handleSubmit(1)">保存</van-button>
    </div>
    <div class="publicBox formDivBox">
      <van-form ref="form" class="byFrom">
        <van-field-checkbox label="保养人员" v-model="ruleForm.userLists" placeholder="请选择保养人员" :columns="userLists" :option="{label:'userName',value:'userId'}" @confirm="chooseUser($event)" />

        <van-field label="实际开始" name="actualStartTime" :rules="[{ required: true, message: '请选择开始时间', trigger: 'blur' }]" v-model="ruleForm.actualStartTime" size="mini" readonly @click="timeChange(1)" />

        <van-field label="实际结束" name="actualEndTime" :rules="[{ required: true, message: '请选择结束时间', trigger: 'blur' }]" v-model="ruleForm.actualEndTime" size="mini" readonly @click="timeChange(2)" />

        <div class="inputRightFont">
          <van-field label="保养工时" disabled :rules="[{ required: true, message: '请输入保养工时', trigger: 'blur' }]" v-model="ruleForm.maintainHours" :max="9999.99" style="width:93%; float: left;" type="number" placeholder="请输入数字" :formatter="formatter" />
          <span class="sp">小时</span>
        </div>
        <van-field name="isFinish" label="工单已完成">
          <template #input>
            <van-checkbox v-model="isFinish" shape="square" :disabled="isDisabled" />
          </template>
        </van-field>

        <van-field v-model="ruleForm.supplementaryDescription" placeholder="请输入补充说明" label="补充说明" rows="3" size="mini" type="textarea" maxlength="200" show-word-limit />

        <p class="pDiv">保养项分类列表</p>
        <van-tabs class="vantTabDiv" @click="itemChange">
          <van-tab v-for="(item,index) in ruleForm.data" :key="index" :title="`${item.classifyName}${'【' + item.classifyCode + '】'}`">
            <ul class="listUl listUlTop">
              <li class="liOne">保养项</li>
              <li class="liTwo">保养项描述</li>
              <li class="liThree">
                <!-- 是否完成 -->
                <van-checkbox v-model="isCheck">是否完成</van-checkbox>
              </li>
            </ul>
            <div class="listUlList">
              <ul class="listUl" v-for="itx in item.itemEntityList" :key="itx.id">
                <li class="liOne">{{ itx.itemName }}{{ itx.itemCode ? `【${itx.itemCode}】`:'' }}</li>
                <li class="liTwo">{{itx.remark || '&nbsp;&nbsp;&nbsp;'}}</li>
                <li class="liThree">
                  <van-checkbox v-model="itx.isFinish" shape="square" />
                </li>
              </ul>
            </div>
          </van-tab>
        </van-tabs>
      </van-form>
    </div>
    <!--  时间选择 -->
    <van-popup v-model="showTime" position="bottom" :style="{ height: '30%' }">
      <van-datetime-picker v-model="currentDate" type="datetime" @confirm="onTimeChange" @cancel="showTime = false" />
    </van-popup>
  </div>
</template>
<script>
import { myFunction, computationTime } from '@/utils/function'
import vanFieldCheckbox from '@/components/selectUser'
export default {
  name: 'RepairRequest',
  components: { vanFieldCheckbox },
  data() {
    return {
      isFinish: '',
      isDisabled: false,
      activeKey: 0,
      currentDate: new Date(),
      userList: [],
      userLists: [],
      ruleForm: {
        userLists: [],
        userList: [],
        supplementaryDescription: '',
        isFinish: '',
        maintainHours: '',
        actualStartTime: '',
        actualEndTime: '',
        itemList: []
      },
      show: false,
      code: localStorage.getItem('code'),
      title: localStorage.getItem('name'),
      search: {
        current: 1,
        size: 5
      },
      list: [],
      loading: false,
      isLoading: false,
      detailsObj: {},
      showTime: false,
      showUser: false,
      nums: null,
      num: null
    }
  },
  computed: {
    isCheck: {
      get() {
        return this.ruleForm.data[this.num].itemEntityList.every(
          (item) => item.isFinish === true
        )
      },
      set(val) {
        this.ruleForm.data[this.num].itemEntityList.forEach(
          (item) => (item.isFinish = val ? true : false)
        )
      }
    }
  },
  watch: {
    ruleForm: {
      deep: true,
      handler(row) {
        if (row) {
          if (computationTime(row.startTime, row.endTime) < 0) {
            row.endTime = ''
            this.$toast.fail('结束时间不能早于开始时间！')
          }
          const list = []
          if (row.data) {
            row.data.forEach((item) => {
              item.itemEntityList.forEach((itx) => {
                list.push(itx)
              })
            })
            const judge = list.every((item) => item.isFinish === true)
            if (judge === true) {
              this.isFinish = true
              this.isDisabled = true
            } else {
              this.isFinish = false
              this.isDisabled = false
            }
          }
        }
      }
    }
  },
  created() {},
  mounted() {
    this.getData()
  },
  methods: {
    /* tabs点击事件 */
    itemChange($event) {
      if ($event) {
        this.num = $event
      } else {
        this.num = 0
      }
    },
    formatter(value) {
      return value.replace(/^(\-)*(\d+)\.(\d{2}).*$/, '$1$2.$3')
    },
    async getData() {
      this.itemChange()
      this.detailsObj = this.$store.state.data
      /* 获取班组下人员 */
      await this.getApplicant()
      /* 获取保养项分类 */
      await this.getItemList(this.detailsObj.id)
      setTimeout(() => {
        this.ruleForm = { ...this.ruleForm, ...this.detailsObj }
        if (
          this.detailsObj.actualStartTime === '' ||
          this.detailsObj.actualEndTime === ''
        ) {
          this.ruleForm.actualStartTime = this.detailsObj.startTime.slice(0, 16)
          this.ruleForm.actualEndTime = myFunction(new Date()).slice(0, 16)
        } else {
          this.ruleForm.actualStartTime = this.detailsObj.actualStartTime.slice(
            0,
            16
          )
          this.ruleForm.actualEndTime = this.detailsObj.actualEndTime.slice(
            0,
            16
          )
        }
        const timloe =
          Date.parse(this.ruleForm.actualEndTime) -
          new Date(this.ruleForm.actualStartTime.replace(/-/g, '/')).getTime()
        if (timloe > 0) {
          this.ruleForm.maintainHours = (timloe / (1000 * 60 * 60)).toFixed(1)
        } else {
          this.ruleForm.maintainHours = '0.0'
        }
      })
    },
    /**
     * @description: 获取保养项
     */
    async getItemList(id) {
      this.loading = true
      const res = await this.$axios.post(
        `/dobo-equip/maintain/task/getItem/${id}`
      )
      if (res?.data.code === 200) {
        if (res.data.data.data.length > 0) {
          const { supplementaryDescription, maintainHours } = this.detailsObj
          this.ruleForm = {
            ...this.ruleForm,
            ...{
              supplementaryDescription: supplementaryDescription,
              maintainHours: maintainHours
            },
            ...res.data.data
          }
        }
        this.ruleForm.data.forEach((item) => {
          item.itemEntityList.forEach((itx) => {
            itx.isFinish = itx.isFinish === 1 ? true : false
          })
        })
        // console.log(this.ruleForm)
        this.loading = false
      }
    },
    /**
     * @description: 获取班组下所有用户
     * @return {*}
     */
    async getApplicant() {
      const res = await this.$axios.get(
        `/dobo-equip/repair/order/in/getGroupUser?groupId=${this.detailsObj.groupId}`
      )
      if (res && res.data.code === 200) {
        /* 默认为指定班组下的所有人员，可修改(保存以后选择默认保存以后的人员) */
        if (this.detailsObj.maintainUserId === '') {
          res.data.data.forEach((item) => {
            this.ruleForm.userLists.push(item.userId)
          })
        } else {
          this.ruleForm.userLists = this.detailsObj.maintainUserId.split(',')
        }
        this.userLists = res.data.data
      }
    },
    /**  选择保养人员 */
    chooseUser(e) {
      this.userLists.forEach((item) => {
        e.forEach((itx) => {
          if (item.userId === itx) {
            this.ruleForm.userList.push(item.userId)
          }
        })
      })
    },
    timeChange(num) {
      this.nums = num
      this.showTime = true
    },
    /* 时间选择赋值 */
    onTimeChange(value) {
      setTimeout(() => {
        if (this.nums === 1) {
          this.ruleForm.actualStartTime = myFunction(value).slice(0, 16)
        } else {
          this.ruleForm.actualEndTime = myFunction(value).slice(0, 16)
        }
        const timloe =
          new Date(this.ruleForm.actualEndTime.replace(/-/g, '/')).getTime() -
          new Date(this.ruleForm.actualStartTime.replace(/-/g, '/')).getTime()
        if (timloe > 0) {
          this.ruleForm.maintainHours = (timloe / (1000 * 60 * 60)).toFixed(1)
        } else {
          this.ruleForm.maintainHours = '0.0'
        }
        this.showTime = false
      }, 500)
    },
    handleSubmit(num) {
      this.$refs.form
        .validate()
        .then(() => {
          this.$dialog
            .confirm({
              title: '提示',
              message: '是否确认提交？'
            })
            .then(() => {
              if (num === 1) {
                this.submitApi(num)
              } else {
                if (this.isFinish === false) {
                  this.$toast.fail('保养工单未结束，不可以转维修！')
                } else {
                  this.submitApi(num)
                }
              }
            })
            .catch(() => {
              return false
            })
        })
        .catch(() => {})
    },
    submitApi(num) {
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '提交中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      const list = []
      const itemLists = []
      this.userLists.forEach((item) => {
        this.ruleForm.userLists.forEach((itx) => {
          if (item.userId === itx) {
            list.push({ userId: item.userId, userName: item.userName })
          }
        })
      })
      this.ruleForm.data.forEach((item) => {
        if (item.itemEntityList) {
          item.itemEntityList.forEach((itx) => {
            itx.isFinish = itx.isFinish === true ? 1 : 0
            itemLists.push(itx)
          })
        }
      })
      this.ruleForm.actualEndTime = this.ruleForm.actualEndTime + ':00'
      this.ruleForm.actualStartTime = this.ruleForm.actualStartTime + ':00'
      this.ruleForm.itemList = itemLists
      this.ruleForm.userList = list
      this.ruleForm.id = this.detailsObj.id
      this.ruleForm.isFinish = this.isFinish === true ? 1 : 0
      delete this.ruleForm.userLists
      this.$axios
        .post('/dobo-equip/maintain/task/report', this.ruleForm)
        .then((res) => {
          if (res.data.code === 200) {
            toast.clear()
            this.$dialog
              .alert({
                title: '提示',
                message: '提交成功!'
              })
              .then(() => {
                if (num === 1) {
                  this.$router.push('/eqMaintain')
                } else {
                  this.detailsObj.nums = 2
                  this.$router.push('/repairRequest')
                  this.$store.commit('getDate', this.detailsObj)
                }
              })
              .catch(() => {})
          } else {
            this.$toast.fail(res.data.msg)
            setTimeout(() => {
              toast.clear()
              this.$router.push('/eqMaintain')
            }, 1000)
          }
        })
        .catch(() => {})
    },
    // 返回
    onClickLeft() {
      const { query } = this.$route
      if (query.path) {
        this.$router.push(`/${query.path}`)
      } else {
        this.$router.push('/eqMaintain')
      }
    }
  }
}
</script>
<style lang='scss' scoped>
.container {
  .saveBtnDiv {
    position: absolute;
    right: 10px;
    top: 10px;
    width: 200px;
    height: 40px;
    text-align: right;
  }
  .pDiv {
    height: 40px;
    line-height: 40px;
  }
  .byFrom {
    height: 100%;
  }
  .vantTabDiv {
    height: calc(100% - 360px);
  }
  .listUlTop {
    height: 40px;
  }
  .listUlList {
    height: calc(100% - 40px);
    overflow-y: auto;
  }
  .listUl {
    padding: 10px 0;
    overflow: hidden;
    li {
      float: left;
      text-align: center;
    }
    .liOne {
      width: 45%;
    }
    .liTwo {
      width: 35%;
    }
    .liThree {
      width: 20%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  /* 右边有文字的input框样式 */
  .inputRightFont {
    overflow: hidden;
    height: 40px;
    line-height: 40px;
    .sp {
      padding-left: 5px;
    }
  }
  .formDivBox {
    .van-field {
      border: 1px solid #f5f5f5;
    }
  }
}
</style>
<style lang='scss'>
// 提交按钮样式
.saveBtnDiv {
  .saveBtns {
    float: right;
    font-size: 16px;
    z-index: 102;
    height: 40px;
    line-height: 40px;
    background: linear-gradient(to top right, #1cacff, #022566);
    border: 1px solid #022566;
    padding: 0 12px;
    .van-button__content {
      display: block;

      .van-button__text {
        text-align: center;
        width: 100%;
        font-size: 20px;
      }
    }
  }
}
.vantTabDiv {
  .van-tabs__content {
    background: #fff;
    height: calc(100% - 50px);
    .van-tab__pane {
      height: 100%;
    }
  }
  .van-tabs__nav {
    background: #eee;
  }
  .van-tabs__line {
    background: #022566;
  }
}
</style>
